package com.yq.cp.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;

public class HmacUtil {

    public static String encrypt(final String src, final String secret) {
        try {
            byte[] key = secret.getBytes(StandardCharsets.UTF_8);
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            SecretKeySpec secretKey = new SecretKeySpec(
                    Arrays.copyOf(sha.digest(key), 16), "HMACSHA256"
            );
            Mac mac = Mac.getInstance("HMACSHA256");
            mac.init(secretKey);
            byte[] hash = mac.doFinal(src.getBytes());
            return Base64.encodeBase64String(hash);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
